package com.dream.dao.impl;

import com.dream.dao.MajorDao;
import com.dream.pojo.Major;
import com.dream.utils.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class MajorDaoImpl implements MajorDao {
    @Override
    public List<Major> findMajorsByDepartId(String departId) {
        return DBUtil.commonQuery(Major.class, "select * from major where dept_id=?",departId);
    }

    @Override
    public long totalCount(String majorName) {
        String sql = "select count(major.major_id) FROM major where 1=1";
        StringBuilder sb = new StringBuilder(sql);
        if(majorName!=null && !"".equals(majorName)){
            sb.append(" and major.major_name like '%"+majorName+"%'");
        }
        return DBUtil.queryCount(sb.toString());
    }

    @Override
    public List<Major> list(String majorName, long pageIndex, long pageSize) {
        String sql = "select * FROM major where 1=1";

        StringBuilder sb = new StringBuilder(sql);
        if(majorName!=null && !"".equals(majorName)){
            sb.append(" and major.major_name like '%"+majorName+"%'");
        }
        sb.append(" limit ?,?");
        return DBUtil.commonQuery(Major.class, sb.toString(),(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public int add(Major major) {
        try {
            DBUtil.commonUpdate("insert into major values (?,?,?,?)",
                    major.getMajorId(),
                    major.getDeptId(),
                    major.getMajorName(),
                    major.getRemark());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Major findById(String majorId) {
        ArrayList<Major> list = DBUtil.commonQuery(Major.class, "select * from major where major_id=?", majorId);
        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

    @Override
    public int update(Major major) {
        try {
            DBUtil.commonUpdate("update major set major_name=?,remark=?,dept_id=? where major_id=?",
                    major.getMajorName(),
                    major.getRemark(),major.getDeptId(),major.getMajorId());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteById(String majorId) {
        try {
            DBUtil.commonUpdate("delete from  major where major_id=?", majorId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
